<template>
  <div>
    <el-form :label-position="'left'" label-width="150px">
      <el-form-item label="资讯类型">
        <el-select v-model="member.consumtationOption" clearable placeholder="资讯类型">
          <el-option
            v-for="item in consumtationOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面">
        <el-upload
          class="avatar-uploader"
          action="https://wxapp.gdhrma.org.cn/api/file/upload-img"
          name="photo"
          :show-file-list="false"
          :on-success="handlePhoto"
          :before-upload="beforeAvatarUpload">
          <img v-if="photoImg" :src="photoImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="member.name" style="width:200px"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="member.desc" style="width:200px"></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input palceholder="数字越小，排序越前" type="number" v-model="member.sortNum" style="width:400px"></el-input>
      </el-form-item>
      <el-form-item label="资讯标签">
        <el-input v-model="tag" palceholder="输入资讯标签" style="width:200px"></el-input>
        <el-button type="primary" @click="addTag">添加</el-button>
      </el-form-item>
      <el-form-item>
        <div class="memberPicWrapper">
          <div class="memberPicDetail" v-for="(item,index) of tagList" :key="index">
            <div>{{item}}</div>
            <img src="../../../static/images/delete.png" alt="" class="delete" @click.stop="deleteTag(item,index)">
          </div>
        </div>
      </el-form-item>
      <el-form-item label="行业">
        <el-select v-model="member.industry" placeholder="选择分类">
          <el-option
            v-for="item in industryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="origin">
        <el-cascader
          placeholder="选择地址"
          :options="PCORIGIN"
          :props="{value:'label'}"
          v-model="member.address"
          class="cascader"
          filterable></el-cascader>
      </el-form-item>
      <el-form-item label="关联需求">
        <el-button size="medium " type="primary" @click="correlationVisible=true">添加</el-button>
        <div class="executorList">
          <div v-for="(item,index) of executorList" :key="index">
            <span style="cursor:pointer;color:#409EFF" @click.stop="showDemandDetail(item.id)">{{item.title}}</span>
            <i class="el-icon-remove" style="cursor:pointer;color:gray" @click.stop="deleteExecutor(index)"></i>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="资讯详情">
        <vue-ueditor-wrap v-model="detail" :config="myConfig"></vue-ueditor-wrap>
      </el-form-item>
      <el-form-item label="是否展示">
        <el-switch
          v-model="status"
          active-color="#13ce66"
          inactive-color="#ff4949" @change="ha"
        >
        </el-switch>
      </el-form-item>
      <div class="add-table-wrapper">
        <el-button type="primary" @click="commit" class="add-table-wrapper-btn">保存</el-button>
      </div>
    </el-form>


    <!-- 关联需求 -->
    <el-dialog title="关联需求" :visible.sync="correlationVisible" @close="initData">
      <el-form>
        <el-form-item label="关联需求">
          <el-select
            v-model="executor"
            filterable
            remote
            :loading="loading"
            placeholder="请输入需求,展示在资讯下方"
            @change="getExecutor"
            :remote-method="searchName"
            style="width:300px"
          >
            <el-option
              v-for="(item,index) in correlationList"
              :key="item.id"
              :label="item.title"
              :value="index">
              <template>
                <div>{{item.title}}&nbsp;&nbsp;&nbsp; <span @click.stop="showDemandDetail(item.id)"
                                                            style="cursor:pointer;color:#409EFF">查看详情</span></div>
              </template>

            </el-option>
          </el-select>
          <el-button size="medium " type="primary" @click="addExecutor">添加</el-button>
          <div class="executorList">
            <div v-for="(item,index) of executorList" :key="index">
              <span style="cursor:pointer;color:#409EFF" @click.stop="showDemandDetail(item.id)">{{item.title}}</span>
              <i class="el-icon-remove" @click.stop="deleteExecutor(index)"></i>
            </div>
          </div>
        </el-form-item>

      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button type="primary" size="medium" @click="correlationVisible=false">保存</el-button>
      </div>
    </el-dialog>
    <!-- 关联需求end -->

    <!-- 需求详情 -->
    <demandDetailDialog :demandDetailVisible.sync="demandDetailVisible" :demandDetail="demandDetail"/>
  </div>
</template>
<script>
  import PCORIGIN from '../../assets/json/pc-code.json';
  import demandDetailDialog from '@/components/demandDetail';

  export default {
    components: {demandDetailDialog},
    data() {
      return {
        detail: '',
        correlationVisible: false,
        demandDetailVisible: false,//需求的详情
        demandDetail: {user_info: {}},
        loading: false,
        PCORIGIN,
        id: '',
        photoImg: '',
        photoID: '',

        consumtationOption: '',//头部筛选的资讯类型
        consumtationOptions: [
          {label: '其他', value: 0}

        ],
        member: {
          consumtationOption: '',
          name: '',
          desc: '',
          sortNum: '',
          industry: '',
          address: [],
          representative: '',
          code: '',
          status: 0
        },
        status: false,
        tag: '',
        tagList: [],

        industryOptions: [{label: '互联网', value: 1}],

        correlationList: [],//模糊搜索的需求
        executor: '',
        executorList: [],//选中关联的需求
        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 500,
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
          // serverUrl: 'http://35.201.165.105:8000/controller.php',
          // https://shop.rzkeji.com/ueditor-php/controller.php
          serverUrl: 'https://wxapp.gdhrma.org.cn/ueditor-php/controller.php',
          // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
          // //UEDITOR_HOME_URL: '/static/UEditor/'
          //UEDITOR_HOME_URL: '/peoples_association_backstage/dist//static/UEditor/'
          toolbars: [
            [
              'undo', 'redo', '|',
              'bold', 'italic', 'underline', 'strikethrough',
              'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
              'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
              'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
              'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
              'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
              'simpleupload', 'insertimage', 'insertvideo', 'music',
              'horizontal', 'date', 'time',
              'inserttable'
            ]
          ]
        }

      }
    },
    methods: {
      ha(e){
        if (e){
          this.member.status = 1
        } else {
          this.member.status = 0
        }
      },
      async getNewsClassifyList() {
        //获取资讯类型
        let res = await this.$api.getNewsClassifyList();
        if (res.data.level == 'success') {
          res.data.data.forEach(item => {
            this.consumtationOptions.push({
              label: item.name,
              value: item.id
            })
          })
        }
      },
      async getIndustryList() {
        //获取行业列表
        let res = await this.$api.getIndustryList();
        if (res.data.level == 'success') {
          this.industryOptions = res.data.data.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          });
        }
      },

      async showDemandDetail(id) {
        let res = await this.$api.getDemandDetail({demand_id: id});
        if (res.data.level == 'success') {
          this.demandDetail = res.data.data
          this.demandDetailVisible = true
        }

      },
      async commit() {
        let params = {
          classify_id: this.member.consumtationOption,
          title: this.member.name,
          desc: this.member.desc,
          info: this.detail,
          img_id: this.photoId,
          label_arr: this.tagList,
          sort: this.member.sortNum,
          province: this.member.address[0] || '',
          city: this.member.address[1] || '',
          area: this.member.address[2] || '',
          address: this.member.addressDetail,
          industry_id: this.member.industry,
          sort: this.member.sortNum,
          link_demand_ids: this.executorList.map(item => {
            return item.id
          }),
          id: this.id,
          status: this.member.status
        };
        let res = await this.$api.sendNewsByAdmin(params);
        if (res.data.level == 'success') {
          this.$message({
            type: 'success',
            message: res.data.message
          })
          setTimeout(() => {
            this.$router.go(-1)
          })

        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })

        }
      },
      beforeAvatarUpload(file) {
        //上传照片前的操作
        // console.log(file,555)
      },
      handlePhoto(res, file) {
        //上传照片成功
        if (res.data) {
          this.photoImg = res.data.img_url;
          this.photoId = res.data.id;
        }
      },
      addTag() {
        if (this.tag == '') {
          this.$message({
            type: 'warning',
            message: '标签不能为空'
          });
          return;

        }
        this.tagList.push(this.tag);
        this.tag = ''
      },
      deleteTag(item, index) {
        //删除资料
        this.tagList.splice(index, 1);
      },

      getExecutor(e) {
        this.executor = e;
      },
      addExecutor() {
        //添加关联需求
        if (isNaN(this.executor) || this.executor === '') {
          return
        }
        const is_join = this.executorList.find(item => {
          //判断是否已经在筛选的队列里
          return item.id == this.correlationList[this.executor].id
        })
        if (is_join) {
          this.executor = '';
          return
        }
        this.executorList.push(this.correlationList[this.executor]);
        this.executor = '';

      },
      deleteExecutor(index) {
        //删除关联需求
        this.executorList.splice(index, 1);
      },
      async getDemandList() {
        //获取需求列表
        let params = {
          status: this.demandStatusOption,
          review: this.examineStatusOption,
          is_shop: this.spreadStatusOption,
          start_time: this.searchTime.startTime,
          end_time: this.searchTime.endTime,
          page: this.page,
          limit: 16,
          keyword: this.searchText
        }
        let res = await this.$api.getDemandList(
          params);
        if (res.data.level == 'success') {
          this.tableData = res.data.data;
          this.totalPage = res.data.page_info.total;
        }
      },
      async searchName(searchText) {
        //搜索需求
        this.loading = true;
        if (!searchText) {
          this.correlationList = [];
          this.loading = false
          return
        }

        let params = {
          keyword: searchText
        }
        let res = await this.$api.getDemandList(params);

        if (res.data.level == 'success') {
          this.correlationList = res.data.data
        }
        this.loading = false
      },
      async getNewsDetail() {
        //获取资讯详情
        let params = {
          id: this.id
        }
        let res = await this.$api.getNewsDetail(params);
        if (res.data.level == 'success') {
          const data = res.data.data
          this.member.consumtationOption = parseInt(data.classify_id);
          this.member.name = data.title;
          this.member.desc = data.desc;
          this.detail = data.info
          this.detail = this.detail.replace(/<img[^>]*>/gi, function (match, capture) {
            return match.replace(/data-src/ig, 'src')
          });
          this.photoId = data.img_id;
          this.photoImg = data.img_url;
          this.member.sortNum = data.sort;
          this.member.address = [data.province, data.city];
          this.industryOption = parseInt(data.industry_id);
          this.tagList = data.label.map(item => {
            return item.name
          })
          this.member.status = parseInt(data.status);
          this.status = this.member.status==1?true:false;
          this.executorList = data.link_demand_info
        }
      },
      initData() {

      }
    },
    mounted() {

      this.id = this.$route.query.id;
      this.getNewsClassifyList();
      this.getIndustryList();
      this.getNewsDetail()
    },
  }
</script>
<style lang="scss" scoped>
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: contain;
  }

  .add-table-wrapper {
    display: flex;
    justify-content: center;
    padding: 30px 0;
  }

  .memberPicWrapper {
    display: flex;
    flex-wrap: wrap;
  }

  .memberPicDetail {
    text-align: center;
    margin: 0 10px;
    position: relative;

    .delete {
      width: 20px;
      height: 20px;
      position: absolute;
      top: -10px;
      right: -10px;
    }
  }

  .dialog-footer {
    text-align: center;
  }

  .executorList {
    display: flex;
    flex-wrap: wrap;

    div {
      margin: 10px;
      border: 1px solid #eee;
      border-radius: 5px;
      padding: 5px 10px;
    }
  }
</style>
